#!/usr/bin/env python3
"""
调试AI推理问题
"""

import requests
import json
import time
import hashlib
from PIL import Image, ImageDraw
import numpy as np
import tempfile
import io

def create_unique_images():
    """创建有明显区别的测试图像"""
    images = []

    # 图像1：纯黑色 - 应该是缓解期
    img1 = Image.new('RGB', (512, 512), (0, 0, 0))
    with tempfile.NamedTemporaryFile(suffix='.jpg', delete=False) as tmp:
        img1.save(tmp.name, 'JPEG', quality=95)
        with open(tmp.name, 'rb') as f:
            data = f.read()
            md5 = hashlib.md5(data).hexdigest()[:8]
            images.append(('pure_black_' + md5, data))

    # 图像2：纯白色 - 应该是缓解期
    img2 = Image.new('RGB', (512, 512), (255, 255, 255))
    with tempfile.NamedTemporaryFile(suffix='.jpg', delete=False) as tmp:
        img2.save(tmp.name, 'JPEG', quality=95)
        with open(tmp.name, 'rb') as f:
            data = f.read()
            md5 = hashlib.md5(data).hexdigest()[:8]
            images.append(('pure_white_' + md5, data))

    # 图像3：红色出血样
    img3 = Image.new('RGB', (512, 512), (255, 0, 0))
    draw = ImageDraw.Draw(img3)
    # 添加一些红色斑点模拟出血
    for _ in range(50):
        x = np.random.randint(0, 512)
        y = np.random.randint(0, 512)
        r = np.random.randint(5, 20)
        draw.ellipse([(x-r, y-r), (x+r, y+r)], fill=(200, 0, 0))
    with tempfile.NamedTemporaryFile(suffix='.jpg', delete=False) as tmp:
        img3.save(tmp.name, 'JPEG', quality=95)
        with open(tmp.name, 'rb') as f:
            data = f.read()
            md5 = hashlib.md5(data).hexdigest()[:8]
            images.append(('bleeding_pattern_' + md5, data))

    # 图像4：溃疡样
    img4 = Image.new('RGB', (512, 512), (255, 200, 150))
    draw = ImageDraw.Draw(img4)
    # 添加溃疡样凹陷
    for _ in range(30):
        x = np.random.randint(0, 512)
        y = np.random.randint(0, 512)
        r = np.random.randint(10, 30)
        draw.ellipse([(x-r, y-r), (x+r, y+r)], fill=(150, 100, 50))
    with tempfile.NamedTemporaryFile(suffix='.jpg', delete=False) as tmp:
        img4.save(tmp.name, 'JPEG', quality=95)
        with open(tmp.name, 'rb') as f:
            data = f.read()
            md5 = hashlib.md5(data).hexdigest()[:8]
            images.append(('ulcer_pattern_' + md5, data))

    return images

def test_ai_detailed():
    """详细测试AI推理"""
    print("="*80)
    print("AI推理详细调试测试")
    print("="*80)

    images = create_unique_images()
    results = []

    for name, image_data in images:
        print(f"\n测试图像: {name}")
        print("-"*60)

        # 发送请求
        try:
            files = {'file': (name + '.jpg', image_data, 'image/jpeg')}

            start_time = time.time()
            response = requests.post("http://localhost:5001/v1/predict",
                                   files=files,
                                   timeout=30)
            end_time = time.time()

            if response.status_code == 200:
                result = response.json()

                # 详细输出
                print(f"响应时间: {end_time - start_time:.3f}秒")
                print(f"任务ID: {result.get('task_id')}")
                print(f"UCEIS总分: {result.get('uceis_score')}")
                print(f"严重程度: {result.get('severity')}")
                print(f"总体置信度: {result.get('confidence', 0):.3f}")

                # 获取详细分数
                detailed = result.get('detailed_scores', {})
                if detailed:
                    print(f"\n详细评分:")
                    print(f"  血管形态(vascular): {detailed.get('vascular', {}).get('score')} (置信度: {detailed.get('vascular', {}).get('confidence', 0):.3f})")
                    print(f"  出血(bleeding): {detailed.get('bleeding', {}).get('score')} (置信度: {detailed.get('bleeding', {}).get('confidence', 0):.3f})")
                    print(f"  侵蚀/溃疡(erosion): {detailed.get('erosion', {}).get('score')} (置信度: {detailed.get('erosion', {}).get('confidence', 0):.3f})")

                    # 概率分布
                    total_probs = detailed.get('total', {}).get('probabilities', [])
                    if total_probs:
                        print(f"\n概率分布 (0-8分):")
                        for i, prob in enumerate(total_probs):
                            print(f"  {i}分: {prob:.3f}")

                # 保存结果
                results.append({
                    'image': name,
                    'uceis_score': result.get('uceis_score'),
                    'confidence': result.get('confidence'),
                    'vascular_score': detailed.get('vascular', {}).get('score'),
                    'bleeding_score': detailed.get('bleeding', {}).get('score'),
                    'erosion_score': detailed.get('erosion', {}).get('score'),
                    'probabilities': detailed.get('total', {}).get('probabilities', []),
                    'response_time': end_time - start_time
                })
            else:
                print(f"错误: HTTP {response.status_code}")
                print(response.text)

        except Exception as e:
            print(f"异常: {str(e)}")

    # 分析结果
    print("\n" + "="*80)
    print("结果分析")
    print("="*80)

    if len(results) > 1:
        scores = [r['uceis_score'] for r in results]
        confidences = [r['confidence'] for r in results]

        print(f"\n图像评分结果:")
        for r in results:
            print(f"  {r['image']}: 评分={r['uceis_score']}, 置信度={r['confidence']:.3f}")

        # 检查是否所有结果都相同
        all_same_score = len(set(scores)) == 1
        all_same_probs = True

        if len(results) > 1:
            first_probs = results[0]['probabilities']
            for r in results[1:]:
                if r['probabilities'] != first_probs:
                    all_same_probs = False
                    break

        print(f"\n分析结果:")
        print(f"  所有图像评分相同: {'是' if all_same_score else '否'}")
        print(f"  所有概率分布相同: {'是' if all_same_probs else '否'}")

        if all_same_score and all_same_probs:
            print("\n⚠️  警告: AI可能没有真正处理图像内容！")
            print("   可能的原因:")
            print("   1. 模型加载失败，使用了默认值")
            print("   2. 图像预处理有问题")
            print("   3. 模型推理被绕过")
        else:
            print("\n✓ AI确实在处理不同的图像")

def check_ai_server_status():
    """检查AI服务器的详细状态"""
    print("\n" + "="*80)
    print("AI服务器状态检查")
    print("="*80)

    try:
        response = requests.get("http://localhost:5001/health", timeout=5)
        if response.status_code == 200:
            data = response.json()
            print(f"服务状态: {data.get('status')}")
            print(f"模型已加载: {'是' if data.get('model_loaded') else '否'}")
            print(f"设备: {data.get('device')}")
            print(f"消息: {data.get('message')}")
        else:
            print(f"健康检查失败: {response.status_code}")
    except Exception as e:
        print(f"无法连接: {str(e)}")

    # 检查根路径
    try:
        response = requests.get("http://localhost:5001/", timeout=5)
        if response.status_code == 200:
            data = response.json()
            print(f"\n服务信息: {json.dumps(data, indent=2, ensure_ascii=False)}")
    except:
        pass

if __name__ == "__main__":
    check_ai_server_status()
    test_ai_detailed()